# -*- coding: utf-8 -*-

import wsgiref.handlers
import sys
import os
import string
import hashlib
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging
import Cookie
import urllib
import urllib2


DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp

webapp.template.register_template_library('customfilters')
webapp.template.register_template_library('smart_if')
template.register_template_library('django.contrib.markup.templatetags.markup')

from math import sqrt
from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from datetime import datetime
from google.appengine.api import images
from models import *
import config
from utilities import *
from login import *
from django.utils import simplejson as json

from feed import *

from youtube import *
import pylast

from google.appengine.ext.webapp import template

os.environ['DJANGO_SETTINGS_MODULE'] = 'conf.settings'
from django.conf import settings
# Force Django to reload settings
settings._target = None

# Set to true if we want to have our webapp print stack traces, etc
_DEBUG = True

_LANG = ''

class BaseRequestHandler(I18NRequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the variables present in this function.
  """
  def generate(self, template_name, template_values={}):

    cookie_django_language = self.request.get('cookie_django_language', '')
    global _LANG
    _LANG = cookie_django_language

    if os.environ["SERVER_NAME"] != "videos.tc":
      if "es." in os.environ["SERVER_NAME"]:
        self.request.COOKIES['django_language'] = 'es'
      elif "de." in os.environ["SERVER_NAME"]:
        self.request.COOKIES['django_language'] = 'de'
      elif "fr." in os.environ["SERVER_NAME"]:
        self.request.COOKIES['django_language'] = 'fr'
      elif "en." in os.environ["SERVER_NAME"]:
        self.request.COOKIES['django_language'] = 'en'
      elif "www." in os.environ["SERVER_NAME"]:
        self.request.COOKIES['django_language'] = 'en'
      elif "pt." in os.environ["SERVER_NAME"]:
        self.request.COOKIES['django_language'] = 'pt'
      elif "it." in os.environ["SERVER_NAME"]:
        self.request.COOKIES['django_language'] = 'it'
      self.reset_language()

    logincontrol = LoginControl()
    dbuser = logincontrol.CheckLogin(self)
    if dbuser == 0:
      logged = False
    else:
      logged = True

    values = {
      'request': self.request,
      'application_name': 'videos.tc',
      'logged': logged,
      'user': dbuser,
      'lang': _LANG
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    self.response.out.write(template.render(path, values, debug=_DEBUG))


class Index(BaseRequestHandler):
  def get(self):

    template_values = {

    }
    self.generate('index.html', template_values)

class Videos(BaseRequestHandler):
  def get(self,kw):
    
    kw = kw.capitalize()
    
    youtube = YouTube()
    videos = youtube.LoadVideos(kw, 'relevance', '20')
    
    template_values = {
      'videos': videos,
      'kw': kw,
    }
    self.generate('videos.html', template_values)

class Video(BaseRequestHandler):
  def get(self,vid):
    
    youtube = YouTube()
    video = youtube.LoadVideo(vid)
    
    title = video.title.text
    thumbnail = video.media.thumbnail[0].url
    description = video.media.description
    category = video.media.category[0]
    urlvideo = video.media.player.url
    date = video.published.text.split('T')[0]
    time = video.published.text.split('T')[1][:5]
    tags = video.media.keywords
    vid = video.id.text
    videoid = vid.split('/')[6]
    author = video.author[0].name.text
    
    template_values = {
      'video': video,
      'title': title,
      'videoid': videoid,
      'date': date,
      'time': time,
      'category': category,
    }
    self.generate('video.html', template_values)

class Search(BaseRequestHandler):
  def get(self):
    q = self.request.get("q")
    
    kw = q.capitalize()
    
    youtube = YouTube()
    videos = youtube.LoadVideos(kw, 'relevance', '20')
    
    template_values = {
      'videos': videos,
      'kw': kw,
    }
    self.generate('videos.html', template_values)

class Contact(BaseRequestHandler):
  def get(self):
    template_values = {}
    self.generate('contact.html', template_values)

  def post(self):
    if self.request.get("send")!="":
      name = self.request.get("name")
      email = self.request.get("email")
      message = self.request.get("message")

      # Send an email to admin
      mailtosend = mail.EmailMessage(sender="info@nucomo.com",subject="Mensaje de contacto de " + name + " - " + email)
      mailtosend.to = "info@nucomo.com"
      mailtosend.reply_to = email
      mailtosend.body = message
      try:
        mailtosend.send()
      except:
        p=0

      template_values = {
        'sent': True,
      }
      self.generate('contact.html', template_values)  


class NotFoundPageHandler(BaseRequestHandler):
  def get(self):
    self.error(404)
    template_values = {}
    self.generate('404.html', template_values)


class ImageView(webapp.RequestHandler):
  def get(self,imageid):
    if 1==1:
    #try:
      file=File.get(imageid)
      if file:
        self.response.headers['Content-Type'] = "image/jpeg"
        self.response.headers['Cache-Control'] = "public, max-age=363600"
        self.response.out.write(file.bytes_content)
      else:
        self.error(500)
        errorlauncher = ErrorLauncher()
        errorlauncher.Launch(self,404)
        return 1
    #except :
      #self.error(500)
      #errorlauncher = ErrorLauncher()
      #errorlauncher.Launch(self,500)
      #return 1


class ImageViewResized(webapp.RequestHandler):
  def get(self,imageid,width,height,action):
    if 1==1:
    #try:
      myfile=File.get(imageid)
      if myfile:
        if action=='resized':
          if height=='auto':
  	    content = myfile.bytes_content
            img=images.Image(content)
            originalwidth = float(img.width)
            originalheight = float(img.height)
            resizedwidth = float(width)
            resizedheight = float(float(originalheight*resizedwidth)/originalwidth)
  	    resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
  	  elif width=='auto':
  	    content = myfile.bytes_content
            img=images.Image(content)
            originalwidth = float(img.width)
            originalheight = float(img.height)
            resizedheight = float(height)
            resizedwidth = float(float(originalwidth*resizedheight)/originalheight)
  	    resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
  	  else:
  	    content = myfile.bytes_content
            img=images.Image(content)
  	    resizedwidth=float(width)
  	    resizedheight=float(height)
  	    resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
  	  self.response.headers['Content-Type'] = "image/jpeg"
  	  self.response.headers['Cache-Control'] = "public, max-age=363600"
  	  self.response.out.write(resizedcontent)
  	elif action=='cropped':
  	  width=float(width)
  	  height=float(height)
  	  content = myfile.bytes_content
          img=images.Image(content)
          originalwidth = float(img.width)
          originalheight = float(img.height)
          resizedwidth = width
          if originalwidth>=originalheight:
            resizedheight = height
            resizedwidth = (originalwidth*resizedheight)/originalheight
          if resizedwidth<=width:
            resizedwidth = width
            resizedheight = (originalheight*resizedwidth)/originalwidth

          resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
          resizedimg=images.Image(resizedcontent)
          originalwidth = resizedimg.width
          originalheight = resizedimg.height
          relativewidth = (width/originalwidth)
          relativeheight = (height/originalheight)
          borderwidth = math.fabs((1 - relativewidth)/2)
          borderheight = math.fabs((1 - relativeheight)/2)
          left_x = borderwidth
          right_x = 1 - borderwidth
          top_y = borderheight
          bottom_y = 1 - borderheight
          croppedcontent=images.crop(resizedcontent, left_x, top_y, right_x, bottom_y)
          self.response.headers['Content-Type'] = "image/jpeg"
          self.response.headers['Cache-Control'] = "public, max-age=363600"
  	  self.response.out.write(croppedcontent)
  	  #print ''
  	  #print str(totalwidth)+'-'+str(left_x)+'-'+str(right_x)+'|'+str(top_y)+'-'+str(bottom_y)
  	else:
  	  self.response.headers['Content-Type'] = "image/jpeg"
  	  self.response.headers['Cache-Control'] = "public, max-age=363600"
  	  self.response.out.write(file.bytes_content)
      else:
        self.error(500)
        errorlauncher = ErrorLauncher()
        errorlauncher.Launch(self,500)
  	return 1
    #except :
      #self.error(500)
      #errorlauncher = ErrorLauncher()
      #errorlauncher.Launch(self,500)
      #return 1

class AddFeed(BaseRequestHandler):
  def get(self):
    template_values = {
    }
    self.generate('addfeed.html', template_values)

  def post(self):
    url = self.request.get("url")
    sourcename = self.request.get("sourcename")

    afeed = Feed(url = url, sourceName = sourcename)
    afeed.put()
    self.redirect('/')
    
def main():
  urlmap = [
            ('/', Index),
            ('/v/(.*)', Video), 
            ('/contact', Contact),
            ('/image/(.*)/(.*)/(.*)/(resized)/', ImageViewResized),
            ('/image/(.*)/(.*)/(.*)/(cropped)/', ImageViewResized),
            ('/image/(.*)/', ImageView),
            ('/search/', Search),
            ('/addfeed/', AddFeed),
            ('/addfeed', AddFeed),
            ('/readfeeds/', FeedManager),
            ('/(.*)', Videos), 
           ]

  url = '/.*'
  rule = (url, NotFoundPageHandler)
  urlmap.append(rule)

  application = webapp.WSGIApplication(urlmap, debug=_DEBUG)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()